import { createRouter, createWebHashHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

import { showConfirmDialog } from "vant";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
      meta: {
        //页面的路由配置中通过meta 记录这个页面是否需要tabbar
        showTabbar: true,
      },
    },
    {
      path: "/cate",
      name: "cate",
      component: () => import("../views/CateView.vue"),
      meta: {
        showTabbar: true,
      },
    },
    {
      path: "/cart",
      name: "cart",
      component: () => import("../views/CartView.vue"),
      meta: {
        showTabbar: true,
        //记录当前页面的是否需要登录权限
        requireLogin: true,
      },
    },
    {
      path: "/my",
      name: "my",
      component: () => import("../views/MyView.vue"),
      meta: {
        showTabbar: true,
        //记录当前页面的是否需要登录权限
        requireLogin: true,
      },
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/LoginView.vue"),
    },
    {
      path: "/reg",
      name: "reg",
      component: () => import("../views/RegView.vue"),
    },
    {
      path: "/detail",
      name: "detail",
      component: () => import("../views/DetailView.vue"),
    },
    {
      path: "/search",
      name: "search",
      component: () => import("../views/SearchResultView.vue"),
    },
    {
      path: "/userInfo",
      name: "userInfo",
      component: () => import("../views/UserInfoView.vue"),
      meta: {
        //记录当前页面的是否需要登录权限
        requireLogin: true,
      },
    },
  ],
});
router.beforeEach((to) => {
  if (to.meta.requireLogin === true) {
    //要访问的页面需要登录权限
    // 判断用户是否已经登录
    let token = localStorage.getItem("xx-mall-token");
    if (token == null) {
      showConfirmDialog({
        title: "消息提示",
        message: "当前没有的登录，是否需要登录",
      })
        .then(() => {
          // on confirm
          router.push("/login");
        })
        .catch(() => {
          // on cancel
        });
      return false;
    }
  }
});

export default router;
